/**
  ******************************************************************************
  * File Name          : syscfg.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "edct.h"
#include "bsp.h"
#include "eeprom.h"
#include <stdio.h>
#include <string.h>

#define EDCT_STORAGE_ADDRESS      EEPROM_BLOCK00

static Edct_StorageParaType edct_storage_para;
static const Edct_ParaType  Edct_InitPara = 
{
  .tvoc_en   = 0u,
  .sdp810_en = 0u,
  .did = "HZ50210315011",
};

Edct_ParaType Edct_RunPara;

uint8_t Edct_ParaCheck(Edct_ParaType *para)
{
	if((para->tvoc_en != 0) && (para->tvoc_en != 1))
	{
		return 1;
	}
	
  if((para->sdp810_en != 0) && (para->sdp810_en != 1))
	{
		return 1;
	}
  
	return 0;
}

/***************************** LOAD *************************************/
static void storage_save_initpara(void)
{
	memset(&edct_storage_para, 0, sizeof(Edct_StorageParaType));
  
  edct_storage_para.para = Edct_InitPara;
  
  edct_storage_para.crc16 = crc16((uint8_t *)&edct_storage_para.para, sizeof(Edct_ParaType));
  
  eEPRom_Write(EDCT_STORAGE_ADDRESS, (const uint8_t*)&edct_storage_para, sizeof(Edct_StorageParaType));
  
  Edct_RunPara = Edct_InitPara;
  
  printf("Edct Init para saved!\r\n");
}

void Storage_xx_save(uint8_t type)
{
  memset(&edct_storage_para, 0, sizeof(Edct_StorageParaType));
  
  edct_storage_para.para = Edct_RunPara;
  
  edct_storage_para.crc16 = crc16((uint8_t *)&edct_storage_para.para, sizeof(Edct_ParaType));
  
  eEPRom_Write(EDCT_STORAGE_ADDRESS, (const uint8_t*)&edct_storage_para, sizeof(Edct_StorageParaType));
  
  printf("Edct para save success.\r\n");
}

uint8_t Storage_xx_load(void)
{
  uint16_t crc;
  
  memset(&edct_storage_para, 0, sizeof(Edct_StorageParaType));
  
  eEPRom_Read(EDCT_STORAGE_ADDRESS, (uint8_t*)&edct_storage_para, sizeof(Edct_StorageParaType));
  
  crc = crc16((uint8_t *)&edct_storage_para.para, sizeof(Edct_ParaType));
  
  if(edct_storage_para.crc16 != crc)
  {
    printf("crc check error:0x%04X, 0x%04X\r\n", edct_storage_para.crc16, crc);
    storage_save_initpara();
    return 1;
  }
  
  if(Edct_ParaCheck(&edct_storage_para.para) != 0)
  {
    storage_save_initpara();
    return 2;
  }
  
  Edct_RunPara = edct_storage_para.para;
  
  _printf("EDCT Parameter load SUCCESS!\r\n");
  _printf("Device ID    : %s\r\n", Edct_RunPara.did);
  _printf("TVOC State   : %d\r\n", Edct_RunPara.tvoc_en);
  _printf("Pres State   : %d\r\n", Edct_RunPara.sdp810_en);
  
  return 0;
}
